package com.conversationboard.filedownload;

import java.io.*;
import java.util.*;

public class FileUtils {

	/**
	 * Read a file into an input array as effciently as possible.
	 * 
	 * @param file
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */

	public static byte[] readFile(File file) throws FileNotFoundException, IOException {

		InputStream inputStream = null;
		byte[] outputBuffer = null;
		int bufferLength = 20000 * 1024;

		try {

			inputStream = new BufferedInputStream(new FileInputStream(file));
			outputBuffer = new byte[bufferLength];
			byte[] tempBuffer = null;

			int length = 0;
			List data = new ArrayList(24);

			while ((length = inputStream.read(outputBuffer, 0, bufferLength)) != -1) {
				tempBuffer = new byte[length];
				System.arraycopy(outputBuffer, 0, tempBuffer, 0, length);
				data.add(tempBuffer);
			}

			length = 0;

			if (data.size() == 1) {
				return (byte[]) data.get(0);
			}

			for (int i = 0; i < data.size(); i++) {
				length += ((byte[]) data.get(i)).length;
			}

			outputBuffer = new byte[length];
			length = 0;

			for (int i = 0; i < data.size(); i++) {
				tempBuffer = (byte[]) data.get(i);
				System.arraycopy(tempBuffer, 0, outputBuffer, length, tempBuffer.length);
				length += tempBuffer.length;
			}

		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}

		return outputBuffer;
	}

}